package com.vca.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenbing
 * @date 2022/2/25 09:26
 */
public class HttpClientUtils {

    final static String proxyHost = "zproxy-sh.cn.ali.rccad.net";
    final static Integer proxyPort = 80;

    private static HttpHost proxy = null;

    private static RequestConfig reqConfig = null;

    public static final String filePath = "F";

    static {
        proxy = new HttpHost(proxyHost, proxyPort, "http");
        reqConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000) // 设置连接超时时间
                .setSocketTimeout(60000) // 设置读取超时时间
                .setExpectContinueEnabled(false).setProxy(new HttpHost(proxyHost, proxyPort))
                .setCircularRedirectsAllowed(true) // 允许多次重定向
                .build();
    }

    public static void main(String[] args) {
        doGetRequest("http://www.baidu.com");
        // doPostRequest();
    }

    public static String doGetRequest(String targetUrl) {
        try {
            HttpGet httpGet = new HttpGet(targetUrl);
            String result = doRequest(httpGet);
            Log.info("Result-----", result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String doPostRequest(String url, Map<String, String> formParams) {
        try {
            // 要访问的目标页面
            HttpPost httpPost = new HttpPost(url);
            // 设置表单参数
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(paramsAdapter(formParams), "utf-8");
            httpPost.setEntity(uefEntity);
            String result = doRequestPost(httpPost);
            Log.info("Result-----", result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return null;
    }

    public static String doRequestPost(HttpRequestBase httpReq) {
        SslUtil.ignoreSsl();
        String result = new String();
        RequestConfig reqConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000) // 设置连接超时时间
                .setSocketTimeout(60000) // 设置读取超时时间
                .setExpectContinueEnabled(false).setProxy(new HttpHost("zproxy-sh.cn.ali.rccad.net", 80))
//                .setExpectContinueEnabled(false).setProxy(new HttpHost("124.223.41.189", 8599))
                .setCircularRedirectsAllowed(true) // 允许多次重定向
                .build();
        httpReq.setConfig(reqConfig);
        CloseableHttpResponse httpResp = null;
        try {
            // 设置请求头
            setHeaders(httpReq);
//            CloseableHttpClient httpClient = new SSLClient();
            // 执行请求
            httpResp = trustAllCertsHttpClient().execute(httpReq, HttpClientContext.create());
//            Log.info("httpResp", JSONObject.toJSONString(httpResp));
            // 获取http code
            int statusCode = httpResp.getStatusLine().getStatusCode();
            System.out.println(statusCode);

            HttpEntity entity = httpResp.getEntity();
//            if (entity != null) {
//                result = EntityUtils.toString(entity, "utf-8");
//            }
            if (null != entity) {
                result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            return null;
        } finally {
            try {
                httpResp.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            httpReq.abort();
        }
        return result;
    }
    public static String sendPostHttpRequestWithTimeOut(String reqURL, HashMap<String, String> sendBody) throws HttpException {
        String result = "-1";
        HttpPost httpPost = new HttpPost(reqURL);
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=" + "UTF-8");
        CloseableHttpResponse response = null;
        try {
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(paramsAdapter(sendBody), "utf-8");
//                StringEntity entity = new StringEntity(param, "UTF-8");
            httpPost.setEntity(uefEntity);
            // 设置请求头
            setHeaders(httpPost);
            httpPost.setConfig(reqConfig);
            response = trustAllCertsHttpClient().execute(httpPost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            throw new HttpException("请求通信[" + reqURL + "]时读取超时，堆栈轨迹如下：", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
        return result;
    }

    public static CloseableHttpClient trustAllCertsHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            // 忽略证书校验
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{
                "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
        final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslConnectionSocketFactory).build();
        // 5秒超时
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000)
                .setSocketTimeout(60000).setConnectTimeout(60000).build();
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(5000).build();
        PoolingHttpClientConnectionManager cm =
                new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setMaxTotal(300);
        // 单路由最大并发数
        cm.setDefaultMaxPerRoute(30);
        return HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setRetryHandler(new StandardHttpRequestRetryHandler())
                .setDefaultSocketConfig(socketConfig).setConnectionManager(cm).build();
    }

    /**
     * 设置请求头
     *
     * @param httpReq
     */
    private static void setHeaders(HttpRequestBase httpReq) {
        httpReq.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36");
    }

    /**
     * 执行请求
     *
     * @param httpReq
     * @return
     */
    public static String doRequest(HttpRequestBase httpReq) {
        String result = new String();
        httpReq.setConfig(reqConfig);
        try {
            // 设置请求头
            setHeaders(httpReq);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 执行请求
            CloseableHttpResponse httpResp = httpClient.execute(httpReq);
            // 获取http code
            int statusCode = httpResp.getStatusLine().getStatusCode();
            System.out.println(statusCode);

            HttpEntity entity = httpResp.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }

            httpResp.close();
            httpClient.close();
            httpReq.abort();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }

    /**
     * 参数适配器，将系统定义的请求参数转换成HttpClient能够接受的参数类型
     *
     * @param map
     * @return HttpClient要求的参数类型
     */
    private static List<NameValuePair> paramsAdapter(Map<String, String> map) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        for (Map.Entry<String, String> entry : map.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return nvps;
    }


    public static String getIp() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    public static String doGet(String url, Map<String, String> param) {

        return doGet(url, param, null);
    }

    public static String doGet(String url, Map<String, String> param, Map<String, String> headParam) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            if (headParam != null) {
                for (String key : headParam.keySet()) {
                    httpGet.addHeader(key, headParam.get(key));
                }
            }

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null, null);
    }

    public static void Connect(HttpGet httpGet) {
        String str = "";//返回结果
        CloseableHttpResponse response = null;
        try {
            //1、创建httpClient
            CloseableHttpClient client = null;
            try {
                //把代理设置到请求配置        代理IP     端口
                HttpHost proxy = new HttpHost("zproxy-sh.cn.ali.rccad.net", 80);
                //超时时间单位为毫秒
                RequestConfig defaultRequestConfig = RequestConfig.custom()
                        .setConnectTimeout(5000).setSocketTimeout(5000)
                        .setProxy(proxy).build();
                client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

                response = client.execute(httpGet);
            } catch (UnknownHostException hostEx) {
                hostEx.printStackTrace();
            }
            //2、获取实体
            HttpEntity entity = response.getEntity();
            //将实体装成字符串
            str = EntityUtils.toString(entity);
            System.out.println("返回结果---" + str);
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String doPost(String url, Map<String, String> param, Map<String, String> headParam) {

        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }

            if (headParam != null) {
                for (String key : headParam.keySet()) {
                    httpPost.addHeader(key, headParam.get(key));
                }
            }

            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;

    }

    public static String doPost(String url, String json, Map<String, String> headParam) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (json != null) {
                httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

                StringEntity se = new StringEntity(json);

                se.setContentType("text/json");
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

                httpPost.setEntity(se);
            }

            if (headParam != null) {

                for (String key : headParam.keySet()) {
                    httpPost.addHeader(key, headParam.get(key));
                }
            }

            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;

    }

    public static String doPost(String url, Map<String, String> param) {
        return doPost(url, param, null);
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}
